package main

import (
	"net/http"

	"github.com/prometheus/client_golang/prometheus/promhttp"
	plog "github.com/prometheus/common/log"
	"github.com/prometheus/common/version"
	"gopkg.in/alecthomas/kingpin.v2"

	"gitee.com/monitor_dev/ucloud_kafka_exporter/ucloud"
)

var (
	versions  string
	buildUser string = "MickeyZZC"
	buildData string
	branch    string
)

func main() {
	var (
		listenAddress    = kingpin.Flag("web.listen-address", "Address to listen on for web interface and telemetry.").Default(":59308").String()
		metricsPath      = kingpin.Flag("web.telemetry-path", "Path under which to expose metrics.").Default("/metrics").String()
		ucloudPrivateKey = kingpin.Flag("ucloud.privatekey", "Ucloud api  PrivateKey.").Default("").String()
		ucloudPublicKey  = kingpin.Flag("ucloud.publickey", "Ucloud api  PublicKey.").Default("").String()
		//reload time
		ucloudKafkaReload    = kingpin.Flag("ucloud.kafkaReload", "Ucloud kafka resource reload interval time,units of minutes,default 100 min").Default("100").Int()
		ucloudKafkaProjectID = kingpin.Flag("ucloud.projectID", "Ucloud projectID").Default("all").String()
	)
	version.Version = versions

	version.BuildUser = buildUser
	version.BuildDate = buildData
	version.Branch = branch
	kingpin.Version(version.Print("ucloud_kafka_exporter"))
	kingpin.HelpFlag.Short('h')
	kingpin.Parse()
	var resource = ucloud.NewResource()

	resource.Registry(*ucloudPrivateKey, *ucloudPublicKey)
	err := resource.Update()
	if err != nil {
		plog.Fatal(err.Error())
	}

	go ucloud.Collector(resource, ucloudKafkaReload, *ucloudKafkaProjectID)

	http.Handle(*metricsPath, promhttp.Handler())
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`<html>
	        <head><title>Ucloud Kafka Exporter</title></head>
	        <body>
	        <h1>Ucloud Kafka Exporter</h1>
	        <p><a href='` + *metricsPath + `'>Metrics</a></p>
	        </body>
	        </html>`))
	})

	plog.Infoln("Listening on", *listenAddress)
	plog.Fatal(http.ListenAndServe(*listenAddress, nil))
}
